//
//  LZVideoDetailViewController.m
//  LzzizDemo
//
//  Created by xbnzd on 16/11/3.
//  Copyright © 2016年 xbnzd. All rights reserved.
//

#import "LZVideoDetailViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "LZVideoDetailBtnsCell.h"
#import "LZVideoDetialTitleAndStarCell.h"
#import "LZVideoDetailTextCell.h"
#import "LZVideoDetailTagsCell.h"
#import "LZVideoDetailRestaurantNameCell.h"
#import "LZVideoDetailAddressAndIphoneCell.h"
#import "LZLocationDistanceView.h"
#import "LZCustomPlayerView.h"
#import "Masonry.h"
#import "UIView+Rotation.h"
#import "UIViewController+NavigationItemSetting.h"
#import "LAReviewTableViewCell.h"
#import "LAReviewModel.h"
#import "LZVideoPresenter.h"
#import "LZUserOperationPresenter.h"
#import "LZVideoPresenter.h"
#import "LZVideoDetialModel.h"
#import "LZVideoReviewListViewController.h"
#import "XBNTimeLimitCountDownCalculator.h"
#import "LZTimeLimitCountDownJudgeDataManager.h"
#import "LZGrabCouponDetailViewController.h"
#import "LZFightGroupDetailViewController.h"
#import "LZPlayVideoManager.h"
#import "LZRestaurantDetailModel.h"
#import "LZLoginViewController.h"
#import "LZUserModel.h"
#import "LZCheckCouponAndGrouponPresenter.h"
#import "LZPromotionStatusModel.h"
#import "LZAlertView.h"
#import "TShareView.h"
#import "TShareEventHandler.h"
#import "extobjc.h"
#import "LZMapModel.h"
#import "LZMapViewController.h"
#import "LZActionSheet.h"
#import "UIImageView+WebCache.h"
#import "LZCuisineModel.h"
#import "LZHomePageViewController.h"
#import "LAMerchantDetailViewController.h"
#import "AppDelegate.h"

static NSString *kBtnsCell  = @"btnscell";
static NSString *kTitleCell = @"titleAndStarCell";
static NSString *kTextCell  = @"textCell";
static NSString *kTagsCell  = @"tagsCell";
static NSString *kResNameCell = @"restaurantNameCell";
static NSString *kAddressIphoneCell = @"addressIphoneCell";

@interface LZVideoDetailViewController ()<UITableViewDelegate,UITableViewDataSource,LZVideoDetailTextCellDelegate,LZVideoDetailBtnsCellDelegate,LAReviewCellDelegate>
{
    NSInteger _introductionLabelNumLines;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *couponBtnBgView;
@property (weak, nonatomic) IBOutlet UIView *groupBtnBgView;
@property (weak, nonatomic) IBOutlet UILabel *couponTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *couponCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *groupTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *groupTimeDownLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewBottomToSuperViewCST;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *couponBtnBgViewTrailingToSuperViewCST;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *groupBtnBgViewLeadingToSuperViewCST;
@property (nonatomic, strong) LZCustomPlayerView *playerView;
@property (nonatomic, strong) UIView *videoBgView;
@property (nonatomic, strong) UIImageView *videoCoverImage;
@property (strong, nonatomic) UIButton *nav_left_back;
@property (assign, nonatomic) CGFloat navbar_change_y;
@property (assign, nonatomic) CGFloat lzAlpha;
@property (nonatomic, strong) NSMutableArray *reviewArray; // 评论列表的数组

@property (nonatomic, strong) LZVideoDetialModel *detailModel;

@property (nonatomic, assign) BOOL isEndTime;

@property (nonatomic, strong) TShareView * shareView;

@property (weak, nonatomic) LZActionSheet * sheetView;

@property (nonatomic, strong) NSArray *cuisineDataArr;           //菜系数据

@property (nonatomic, assign) NSTimeInterval currentTimeStamp;

@property (nonatomic, assign) BOOL timeLimitIsNotNilFromeBeforeVC;  //标记,从上个页面传入的倒计时不为nil

@end

@implementation LZVideoDetailViewController
- (id)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"视频详情页面";
    
    self.couponBtnBgView.backgroundColor = UIColorFromRGB(0xff7a21, 1);
    self.couponTitleLabel.text = LZLocalizedString(@"get_coupon", nil);
    self.groupTitleLabel.text = LZLocalizedString(@"group_order", nil);
    _introductionLabelNumLines = 3;
    _reviewArray = [NSMutableArray array];
    [self initLocalData];
    [self configNavigationBar];
    [self regsterHeaderAndCell];
    if (self.limitCountDownCalculator != nil) {
        self.timeLimitIsNotNilFromeBeforeVC = YES;
        [self startTimeDownAction];
    }else{
        self.timeLimitIsNotNilFromeBeforeVC = NO;
    }
    
    [self getData];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self releasePlayViewRAM];
}

- (void)dealloc
{
    DLog(@"dealloc");
}

- (BOOL)fd_prefersNavigationBarHidden {
    return YES;
}

#pragma mark -
#pragma mark network data
- (void)getData
{
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:NO];
    @weakify(self);
    [LZVideoPresenter getVideoDetailWithVideoID:_videoID ResultSuccess:^(LZVideoDetialModel *model, NSTimeInterval timeStamp) {
        @strongify(self);
        
        self.detailModel = model;
        self.currentTimeStamp = timeStamp;
        
        [self configureFootBtnFrame];
        
        if (self.timeLimitIsNotNilFromeBeforeVC == NO) {
            [self startTimeDownAction];
        }
        
        [self.reviewArray addObjectsFromArray:model.commentList];
        
        self.couponCountLabel.text = [NSString stringWithFormat:@"%ld %@",model.couponsTotalCount - model.couponsGetCount,LZLocalizedString(@"group_left_big", nil)];
        
        [self.videoCoverImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,model.videoPhoto]] placeholderImage:[UIImage imageNamed:@"videoCoverImg"]];
        
        [self.tableView reloadData];
        
        [self playVideo];
        
        if (self.updateNumBlock) {
            self.updateNumBlock(model.likesCount,model.storeCount,model.remarkCountPerson,model.shareCount);
        }

        [self stopLoadingViewForView:self.view];
    } ResuleFailed:^(NSString *errorRemind) {
        [self stopLoadingViewForView:self.view];
    }];
}  

- (void)configureFootBtnFrame
{
    GET_SCREEN_WIDTH(sWidth);
    if (self.detailModel.couponsName.length > 0 && self.detailModel.grouponName.length > 0) {
        
        self.couponBtnBgView.hidden = NO;
        self.groupBtnBgView.hidden = NO;
        self.couponBtnBgViewTrailingToSuperViewCST.constant = sWidth/2;
        self.groupBtnBgViewLeadingToSuperViewCST.constant = sWidth/2;
        self.tableViewBottomToSuperViewCST.constant = 46;
        
    }else if (self.detailModel.couponsName.length == 0 && self.detailModel.grouponName.length == 0){
        
        self.couponBtnBgView.hidden = YES;
        self.groupBtnBgView.hidden = YES;
        self.tableViewBottomToSuperViewCST.constant = 0;
        
    }else if (self.detailModel.couponsName.length > 0 && self.detailModel.grouponName.length <= 0){
        
        self.couponBtnBgView.hidden = NO;
        self.groupBtnBgView.hidden = YES;
        self.couponBtnBgViewTrailingToSuperViewCST.constant = 0;
        self.tableViewBottomToSuperViewCST.constant = 46;
        
    }else if (self.detailModel.couponsName.length <= 0 && self.detailModel.grouponName.length > 0){
        
        self.couponBtnBgView.hidden = YES;
        self.groupBtnBgView.hidden = NO;
        self.groupBtnBgViewLeadingToSuperViewCST.constant = 0;
        self.tableViewBottomToSuperViewCST.constant = 46;
    }
}

- (void)zanVideoAction
{
    if ([self checkLoginState]) {
        // 如果已登录
        @weakify(self);
        [LZUserOperationPresenter zanOrCancelZanVideoOrRestaurantWithSellerID:self.detailModel.sellerId PromotionID:self.detailModel.videoId Type:@"1" OperationType:@"1" ResultSuccess:^(NSInteger totleCount, NSInteger operationType) {
            @strongify(self);
            self.detailModel.isLiked = operationType == 1 ? YES : NO;;
            self.detailModel.likesCount = totleCount;
            [self.tableView reloadData];
            if (self.operationZanBlock) {
                self.operationZanBlock(totleCount,operationType);
            }
        } ResultFailed:^(NSString *remind) {
            DLog(@"===%@",remind);
        }];
    }
    
}

- (void)collectVideoAction
{
    if ([self checkLoginState]) {
        // 如果已登录
        NSString *oType = @"1";
        if (self.detailModel.isStore) {
            oType = @"0";
        }
        @weakify(self);
        [LZUserOperationPresenter collectOrCancelCollectVideoOrRestaurantWithSellerID:self.detailModel.sellerId PromotionID:self.detailModel.videoId FavoriteType:@"1" OperationType:oType ResultSuccess:^(NSInteger totleCount, NSInteger operationType) {
            @strongify(self);
            self.detailModel.isStore = operationType == 1 ? YES : NO;
            self.detailModel.storeCount = totleCount;
            [self.tableView reloadData];
            if (self.operationCollectBlock) {
                self.operationCollectBlock(totleCount, operationType);
            }
        } ResultFailed:^(NSString *remind) {
            DLog(@"%@",remind);
        }];
    }
}

- (void)shareAddAction
{
    @weakify(self);
    [self.shareView shareViewOpen];
    self.shareView.shareViewButtonActionBlock = ^(TSHAREVIEW_BUTTON_TYPE type){
        @strongify(self);
        [self shareAction:type videoModel:self.detailModel totleCount:self.operationShareBlock];
    };
}


#pragma mark -
#pragma mark private method
/**
 设置倒计时
 */
-(void)startTimeDownAction
{
    if (self.timeLimitIsNotNilFromeBeforeVC == NO) {
        self.limitCountDownCalculator = [XBNTimeLimitCountDownCalculator new];
        self.limitCountDownCalculator.remainTimeInterval = self.detailModel.grouponEndTime/1000 - self.currentTimeStamp/1000;
    }
    
    @weakify(self);
    [self.limitCountDownCalculator addProcessBlock:^(NSTimeInterval remain) {
        @strongify(self);
        if (remain<=0) {
            self.isEndTime = YES;
            [LZTimeLimitCountDownJudgeDataManager configLimitedLabel:self.groupTimeDownLabel withReamin:0 andDayUnit:@"D " HourUnit:@"H " andMinuteUnit:@"M " andSecUnit:@"S " andIsChangeUintColor:NO andDayUnitColor:nil HourUnitColor:nil andMinUnitColor:nil andSecUnitColor:nil];
        }
        else {
            [LZTimeLimitCountDownJudgeDataManager configLimitedLabel:self.groupTimeDownLabel withReamin:remain andDayUnit:@"D " HourUnit:@"H " andMinuteUnit:@"M " andSecUnit:@"S " andIsChangeUintColor:NO andDayUnitColor:nil HourUnitColor:nil andMinUnitColor:nil andSecUnitColor:nil];
        }
        
    } cancelBlock:^{
        
    }];
    
    if (self.timeLimitIsNotNilFromeBeforeVC == NO) {
        [self.limitCountDownCalculator timeLimitCountDownResume];
    }
}

-(void)configNavigationBar{
    
    self.nav_left_back = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nav_left_back.frame = CGRectMake(0, 0, 60, 40);
    [self.nav_left_back addTarget:self action:@selector(navbarBackButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image_back = [UIImage imageNamed:@"navigationbar_back_circle"];
    [self.nav_left_back setImage:image_back forState:UIControlStateNormal];
    self.nav_left_back.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGRectGetWidth(self.nav_left_back.bounds)-image_back.size.width);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [self.nav_left_back setLanguageRotaion];
    }
    
    
    [self hiddenBarNavigationItemSetting:@[self.nav_left_back] type:NAVIGATIONITEMSETTING_LEFT];
    
    [self lz_setCustomBarAlpha:self.lzAlpha];
}


/**
 播放视频
 */
- (void)playVideo
{
    [[LZPlayVideoManager shareManager] playVideoWithBgView:self.videoBgView playerView:self.playerView videoURL:self.detailModel.videoUrl videoID:self.detailModel.videoId playCountAddBlock:^(NSInteger totleCount) {
        
    }];
}

/**
 离开页面,释放播放器内存
 */
- (void)releasePlayViewRAM
{
   [[LZPlayVideoManager shareManager] stopPlayWithPlayerView:self.playerView];
}

-(void)navbarBackButtonClickAction:(UIButton*)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

// 查看店家地址
- (void)checkMap
{
    LZMapModel *mapModel = [[LZMapModel alloc] init];
    mapModel.longitude = self.detailModel.sellerUser.mapLocationLongitude;
    mapModel.latitude = self.detailModel.sellerUser.mapLocationLatitude;
    mapModel.title = self.detailModel.restaurantName;
    mapModel.content = self.detailModel.sellerUser.restaurantAddress;
    
    LZMapViewController *mapVC = [[LZMapViewController alloc]init];
    mapVC.restaurantModel = mapModel;
    [self.navigationController pushViewController:mapVC animated:YES];
}

// 拨打店家电话
- (void)callPhone:(NSString*)phoneNumber {
    NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",[phoneNumber stringByReplacingOccurrencesOfString:@" " withString:@""]]];
    [[UIApplication sharedApplication] openURL:phoneURL];
}

- (BOOL)checkLoginState {
    if ([[LZUserModel Instance] isLogin]) {
        return YES;
    }
    else {
        // 如果未登录
        LZLoginViewController * vc = [[LZLoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
        return NO;
    }
}

- (NSString *)returnCuisineWithCuisineIDStr:(NSString *)str
{
    if (str.length == 0) {
        return @"";
    }
    
    NSString *returnStr = @"";
    NSArray *idArr = [str componentsSeparatedByString:@","];
    for (int i = 0; i < idArr.count; i ++) {
        NSString *idStrTemp = idArr[i];
        
        NSArray *arrResult = [self.cuisineDataArr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.cuisineID = %@",idStrTemp]];
        
        if (arrResult.count>0) {
            LZCuisineModel *m = arrResult[0];
            if (i == idArr.count - 1) {
                returnStr = [returnStr stringByAppendingString:m.name];
            }else{
                returnStr = [returnStr stringByAppendingString:[NSString stringWithFormat:@"%@,",m.name]];
            }
        }
    }
    
    return returnStr;
}

#pragma mark -
#pragma mark btn action

/**
 点击查看更多评价
 */
- (void)showMoreReviewsAction
{
    LZVideoReviewListViewController *vc = [[LZVideoReviewListViewController alloc] init];
    vc.videoId = [self.detailModel.videoId copy];
    vc.restaurantId = [self.detailModel.sellerId copy];
    [self.navigationController pushViewController:vc animated:YES];
}


/**
 点击进入抢券详情

 @param sender <#sender description#>
 */
- (IBAction)getCouponBtnAction:(id)sender {
    
    if ([self checkLoginState]) {
        // 如果已登录
        if (self.detailModel.isCoupons) {
            DLog(@"已抢券");
            [self showAlertView:LZLocalizedString(@"coupon_geted_remind", nil)];
        }else if (self.detailModel.couponsGetCount == self.detailModel.couponsTotalCount){
            DLog(@"优惠券抢完");
            [self showAlertView:LZLocalizedString(@"coupon_closed_remind", nil)];
        }
        else {
            [self setButtonsUserInteractionEnabled:NO];
            WS(weakSelf)
            [LZCheckCouponAndGrouponPresenter checkCouponWithPromotionId:self.detailModel.videoId ResultSuccess:^(id result) {
                [weakSelf setButtonsUserInteractionEnabled:YES];
                LZPromotionStatusModel *modelTemp = (LZPromotionStatusModel*)result;
                
                if (modelTemp.isPromotion) {
                    weakSelf.detailModel.isCoupons = YES;
                    DLog(@"已抢券");
                    [self showAlertView:LZLocalizedString(@"coupon_geted_remind", nil)];
                }
                else if (modelTemp.isExpired) {
                    [self showAlertView:LZLocalizedString(@"coupon_expired_remind", nil)];
                    DLog(@"已过期");
                }
                else if (modelTemp.isOffLine) {
                    DLog(@"商家已下线");
                    [self showAlertView:LZLocalizedString(@"restaurant_offline_remind", nil)];
                }
                else if (modelTemp.isNull) {
                    weakSelf.detailModel.couponsGetCount = weakSelf.detailModel.couponsTotalCount;
                    [self showAlertView:LZLocalizedString(@"coupon_closed_remind", nil)];
                    DLog(@"已抢完");
                }
                else {
                    LZGrabCouponDetailViewController *vc = [[LZGrabCouponDetailViewController alloc] init];
                    vc.videoID = weakSelf.detailModel.videoId;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
            } ResultFailed:^(NSString *remind) {
                [weakSelf setButtonsUserInteractionEnabled:YES];
            }];
        }
    }
}


/**
 点击进入拼团详情

 @param sender <#sender description#>
 */
- (IBAction)fightGroupAction:(id)sender {
    
    if ([self checkLoginState]) {
        // 如果已登录
        if (self.detailModel.isGroupon) {
            DLog(@"已参团");
            [self showAlertView:LZLocalizedString(@"group_joined_remind", nil)];
        }
        else if (self.isEndTime) {
            DLog(@"倒计时结束");
            [self showAlertView:LZLocalizedString(@"group_closed_remind", nil)];
        }
        else {
            [self setButtonsUserInteractionEnabled:NO];
            WS(weakSelf)
            [LZCheckCouponAndGrouponPresenter checkGrouponWithPromotionId:self.detailModel.videoId ResultSuccess:^(id result) {
                [weakSelf setButtonsUserInteractionEnabled:YES];
                LZPromotionStatusModel *modelTemp = (LZPromotionStatusModel*)result;
                
                if (modelTemp.isPromotion) {
                    weakSelf.detailModel.isGroupon = YES;
                    DLog(@"已参团");
                    [weakSelf showAlertView:LZLocalizedString(@"group_joined_remind", nil)];
                }
                else if (modelTemp.isExpired) {
                    DLog(@"已过期");
                    weakSelf.isEndTime = YES;
                    [weakSelf showAlertView:LZLocalizedString(@"group_closed_remind", nil)];
                }
                else if (modelTemp.isOffLine) {
                    DLog(@"商家已下线");
                    [weakSelf showAlertView:LZLocalizedString(@"restaurant_offline_remind", nil)];
                }
                else {
                    LZFightGroupDetailViewController *vc = [[LZFightGroupDetailViewController alloc] init];
                    vc.videoID = weakSelf.detailModel.videoId;
                    vc.limitCountDownCalculator = weakSelf.limitCountDownCalculator;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
            } ResultFailed:^(NSString *remind) {
                [weakSelf setButtonsUserInteractionEnabled:YES];
            }];
        }
    }
}

- (void)showAlertView:(NSString*)message {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:message andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
}

#pragma mark -
#pragma mark init UI
- (void)initLocalData
{
    self.navbar_change_y = SCREEN_WIDTH/375.0*(500-40)/2.0-64;
    AppDelegate *del = (AppDelegate *) [UIApplication sharedApplication].delegate;
    UITabBarController *rootVc = (UITabBarController *) del.window.rootViewController;
    UINavigationController *navVc = rootVc.viewControllers[0];
    for (id vc in navVc.viewControllers) {
        if ([vc isKindOfClass:[LZHomePageViewController class]]) {
            LZHomePageViewController *homeVc = (LZHomePageViewController *) vc;
            self.cuisineDataArr = homeVc.cuisineArr;
        }
    }
}

- (void)regsterHeaderAndCell
{
//    self.tableView.estimatedRowHeight = 44.0;
//    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"LZVideoDetailBtnsCell" bundle:nil] forCellReuseIdentifier:kBtnsCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZVideoDetialTitleAndStarCell" bundle:nil] forCellReuseIdentifier:kTitleCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZVideoDetailTextCell" bundle:nil] forCellReuseIdentifier:kTextCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZVideoDetailTagsCell" bundle:nil] forCellReuseIdentifier:kTagsCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZVideoDetailRestaurantNameCell" bundle:nil] forCellReuseIdentifier:kResNameCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZVideoDetailAddressAndIphoneCell" bundle:nil] forCellReuseIdentifier:kAddressIphoneCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LAReviewTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    [self.videoBgView addSubview:self.videoCoverImage];
    self.tableView.tableHeaderView = self.videoBgView;
}

- (void)setButtonsUserInteractionEnabled:(BOOL)userInteractionEnabled {
    self.couponBtnBgView.userInteractionEnabled = userInteractionEnabled;
    self.groupBtnBgView.userInteractionEnabled = userInteractionEnabled;
}

#pragma mark -
#pragma mark tableview delegate 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 4;
    }else if (section == 1){
        return 3;
    }
    return self.reviewArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WS(wSelf);
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                return 40;
                
                break;
            case 1:
                return [tableView fd_heightForCellWithIdentifier:kTitleCell cacheByIndexPath:indexPath configuration:^(id cell) {
                    LZVideoDetialTitleAndStarCell *cellTemp = (LZVideoDetialTitleAndStarCell *)cell;
                    [cellTemp getCellTitleLabel].preferredMaxLayoutWidth = SCREEN_WIDTH-20;
                    [cellTemp loadTitle:wSelf.detailModel.promotionTitle StarCount:wSelf.detailModel.remarkCountScore];
                }];
                break;
            case 2:{
                return [tableView fd_heightForCellWithIdentifier:kTextCell configuration:^(id cell) {
                    
                    LZVideoDetailTextCell *cellTemp = (LZVideoDetailTextCell *)cell;

                    [cellTemp cellCuisineLabel].preferredMaxLayoutWidth = SCREEN_WIDTH-[cellTemp cellTitleIngredientsLabel].intrinsicContentSize.width-30;
                    
                    [cellTemp cellIngredientsLabel].preferredMaxLayoutWidth = SCREEN_WIDTH-[cellTemp cellTitleIngredientsLabel].intrinsicContentSize.width-30;
                    
                    [cellTemp cellIntroductionLabel].preferredMaxLayoutWidth = SCREEN_WIDTH - [cellTemp cellTitleIngredientsLabel].intrinsicContentSize.width-30;
                    
                    [cellTemp cellIntroductionLabel].numberOfLines = _introductionLabelNumLines;
                    
                    [cellTemp loadCuisine:[wSelf returnCuisineWithCuisineIDStr:wSelf.detailModel.sellerUser.cookingStyle] Ingredients:wSelf.detailModel.promotionFood Introduction:wSelf.detailModel.profile];

                }];
            }
                
                break;
            case 3:
                return [tableView fd_heightForCellWithIdentifier:kTagsCell cacheByIndexPath:indexPath configuration:^(id cell) {
                    LZVideoDetailTagsCell *cellTemp = (LZVideoDetailTagsCell *)cell;
                    [cellTemp loadTags:self.detailModel.tag];
                }];
                break;
            default:
                break;
        }

    }else if (indexPath.section == 1){
        switch (indexPath.row) {
            case 0:
                return [tableView fd_heightForCellWithIdentifier:kResNameCell cacheByIndexPath:indexPath configuration:^(id cell) {
                    LZVideoDetailRestaurantNameCell *cellTemp = (LZVideoDetailRestaurantNameCell *)cell;
                    [cellTemp loadRestaurantName:wSelf.detailModel.restaurantName StarLevel:[wSelf.detailModel.sellerUser.averageScore floatValue]];
                }];
                break;
            case 1:
                return [tableView fd_heightForCellWithIdentifier:kAddressIphoneCell cacheByIndexPath:indexPath configuration:^(id cell) {
                    LZVideoDetailAddressAndIphoneCell *cellTemp = (LZVideoDetailAddressAndIphoneCell *)cell;
                    [cellTemp loadLabelText:wSelf.detailModel.sellerUser.restaurantAddress CellIcon:[UIImage imageNamed:@"map_location_icon_unselect"]];
                }];
                break;
            case 2:
                return [tableView fd_heightForCellWithIdentifier:kAddressIphoneCell cacheByIndexPath:indexPath configuration:^(id cell) {
                    LZVideoDetailAddressAndIphoneCell *cellTemp = (LZVideoDetailAddressAndIphoneCell *)cell;
                    [cellTemp loadLabelText:wSelf.detailModel.sellerUser.cellphone CellIcon:[UIImage imageNamed:@"icon_手机"]];
                }];
                break;

                
            default:
                break;
        }

    }else if (indexPath.section == 2){
        LAReviewModel *model = self.reviewArray[indexPath.row];
        
        float height = [tableView fd_heightForCellWithIdentifier:@"cell" cacheByIndexPath:indexPath configuration:^(LAReviewTableViewCell *cell) {
            
            [cell getReviewLabel].numberOfLines = model.labReviewNumberOfLine;
            
            [self configureCell:cell atIndexPath:indexPath];
        }];
        
        return height;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    
    return 54;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        return  51;
    }
    
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        return [self creatMoreReviewsFootView];
    }
    UIView *v = [self creatSectionFootView];
    
    return v;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (section == 1) {
        UIView *bgView = [self creatSectionHeadView];
        UILabel *titleLabel = [self creatSectionHeadTitleLabel];
        titleLabel.text = LZLocalizedString(@"restaurant", nil);

        [bgView addSubview:titleLabel];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.mas_equalTo(10);
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.trailing.mas_equalTo(-60);
        }];
        
        if (self.detailModel.sellerUser.distance.length > 0) {
            LZLocationDistanceView *distanceView = [[LZLocationDistanceView alloc]initWithText:@"500m"];
            [bgView addSubview:distanceView];
            
            [distanceView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.trailing.mas_equalTo(-10);
                make.centerY.equalTo(titleLabel);
            }];
        }
        
        
        return bgView;

    }else if(section == 2){
        UIView *bgView = [self creatSectionHeadView];
        UILabel *titleLabel = [self creatSectionHeadTitleLabel];
        titleLabel.text = LZLocalizedString(@"reviews", nil);
        [bgView addSubview:titleLabel];
        
        UILabel *countLabel = [self creatReviewsCountLabel];
        countLabel.text = [NSString stringWithFormat:@"%ld",self.detailModel.remarkCountPerson];
        [bgView addSubview:countLabel];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.mas_equalTo(10);
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.trailing.mas_equalTo(-120);
        }];
        
        CGFloat textW = [self getReviewsTextWidth:[NSString stringWithFormat:@"%ld",self.detailModel.remarkCountPerson]];
        [countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(-10);
            make.centerY.equalTo(titleLabel);
            make.size.mas_equalTo(CGSizeMake(textW + 20, 16));
        }];
        
        return bgView;

    }
    
    return nil;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:{
                LZVideoDetailBtnsCell *cell = [tableView dequeueReusableCellWithIdentifier:kBtnsCell];
                cell.btnsCellDelegate = self;
                [cell loadZanNum:self.detailModel.likesCount CollectNum:self.detailModel.storeCount MsgNum:self.detailModel.remarkCountPerson ShareNum:self.detailModel.shareCount];
                [cell setCollectIconStateIsSelected:self.detailModel.isStore];
                if (self.detailModel.isLiked) {
                    [cell setZanIconSelectedState];
                }
                return cell;
            }
            case 1:{
               
                LZVideoDetialTitleAndStarCell *cell = [tableView dequeueReusableCellWithIdentifier:kTitleCell];
                [cell getCellTitleLabel].preferredMaxLayoutWidth = SCREEN_WIDTH - 20;
                CGFloat starLevel = self.detailModel.remarkCountScore / self.detailModel.remarkCountPerson;
                [cell loadTitle:self.detailModel.promotionTitle StarCount:starLevel];
                return cell;
            }
                
                break;
            case 2:{
                LZVideoDetailTextCell *cell = [tableView dequeueReusableCellWithIdentifier:kTextCell];
                [cell loadCuisine:[self returnCuisineWithCuisineIDStr:self.detailModel.sellerUser.cookingStyle] Ingredients:self.detailModel.promotionFood Introduction:self.detailModel.profile];
                cell.textCellDelegate = self;
                cell.selfIndexPath = indexPath;
                
                return cell;
            }
                
                break;
            case 3:{
                LZVideoDetailTagsCell *cell = [tableView dequeueReusableCellWithIdentifier:kTagsCell];
                [cell loadTags:self.detailModel.tag];
                return cell;
            }
                
                break;
            default:
                break;
        }

    }else if (indexPath.section == 1){
        switch (indexPath.row) {
            case 0:{
                
                LZVideoDetailRestaurantNameCell *cell = [tableView dequeueReusableCellWithIdentifier:kResNameCell];
                [cell loadRestaurantName:self.detailModel.restaurantName StarLevel:[self.detailModel.sellerUser.averageScore floatValue]];
                return cell;
            }
                
                break;
            case 1:{
                LZVideoDetailAddressAndIphoneCell *cell = [tableView dequeueReusableCellWithIdentifier:kAddressIphoneCell];
                [cell loadLabelText:self.detailModel.sellerUser.restaurantAddress CellIcon:[UIImage imageNamed:@"map_location_icon_unselect"]];
                return cell;
            }
                
                break;
            case 2:{
                 LZVideoDetailAddressAndIphoneCell *cell = [tableView dequeueReusableCellWithIdentifier:kAddressIphoneCell];
                [cell loadLabelText:self.detailModel.sellerUser.cellphone CellIcon:[UIImage imageNamed:@"icon_手机"]];
                return cell;
            }
                
                break;
                
            default:
                break;
        }

    }else if (indexPath.section == 2){
        LAReviewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [self configureCell:cell atIndexPath:indexPath];

        return cell;
    }

    return nil;
}

- (void)configureCell:(LAReviewTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO; // Enable to use "-sizeThatFits:"
    
    cell.indexPath = indexPath;
    cell.delegate = self;
    cell.reviewType = ReviewType_Video;
    cell.headImageType = HeadImageType_User;
    
    cell.entity = self.reviewArray[indexPath.row];
    cell.isHideBottomLine = (self.reviewArray.count-1 == indexPath.row);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            [self checkMap];
        }else if (indexPath.row == 2){
            [self showSheetView:self.detailModel.sellerUser.cellphone];
        }else if (indexPath.row == 0){
            LAMerchantDetailViewController *vc = [[LAMerchantDetailViewController alloc] init];
            vc.restaurantId = [self.detailModel.sellerId copy];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (offsetY <= self.navbar_change_y) {
        CGFloat alpha = MIN(1, offsetY/self.navbar_change_y);
        
        self.lzAlpha = alpha;
        
        CGFloat navbar_item_alpha = fabs((alpha-0.5)/(0.5));
        self.nav_left_back.alpha = navbar_item_alpha;
        if (alpha <= 0.5) {
            [self.nav_left_back setImage:[UIImage imageNamed:@"navigationbar_back_circle"] forState:UIControlStateNormal];
        }
        else {
            [self.nav_left_back setImage:[UIImage imageNamed:@"navigationbar_back"] forState:UIControlStateNormal];
        }
        
    } else {
        self.lzAlpha = 1;
    }
    [self lz_setCustomBarAlpha:self.lzAlpha];

}


#pragma mark -
#pragma mark  cell delegate

/**
   LAReviewTableViewCell  delegate
 */
-(void)refreshCellHeight:(NSIndexPath *)indexPath {
    [self.tableView reloadData];
}

/**
 cell 简介,点击查看更多

 */
- (void)clickMoreBtnWithIndexPath:(NSIndexPath *)indxP withBtn:(UIButton *)btn
{
    if (_introductionLabelNumLines == 3) {
        _introductionLabelNumLines = 0;
        
    }else{
        _introductionLabelNumLines = 3;
        
    }
    [self.tableView reloadData];
}


/**
 点击按钮协议 0:分享  1:信息  2:收藏   3:点赞

 */
- (void)clickBtnsWithBtnTag:(NSNumber *)btnTag
{
    switch ([btnTag intValue]) {
        case 0:{//分享
            [self shareAddAction];
        }
            break;
        case 1:{//评论
            [self showMoreReviewsAction];
        }
            break;
        case 2:{//收藏
            [self collectVideoAction];
        }
            break;
        case 3:{//点赞
            [self zanVideoAction];
        }
            break;
            
        default:
            break;
    }
}



#pragma mark -
#pragma mark 空间初始化
- (UIView *)videoBgView
{
    if (!_videoBgView) {
        _videoBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
        _videoBgView.backgroundColor = [UIColor blackColor];
    }
    
    return _videoBgView;
}

- (UIImageView *)videoCoverImage
{
    if (!_videoCoverImage) {
        _videoCoverImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
        _videoCoverImage.backgroundColor = [UIColor blackColor];
        
        _videoCoverImage.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playVideo)];
        [_videoCoverImage addGestureRecognizer:tap];
    }
    
    return _videoCoverImage;
}

- (LZCustomPlayerView *)playerView
{
    if (!_playerView) {
        _playerView = [[LZCustomPlayerView alloc] init];
        _playerView.playCircle = NO;
    }
    
    return _playerView;
}

- (UIView *)creatSectionHeadView
{
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 54)];
    v.backgroundColor = [UIColor whiteColor];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = UIColorFromRGB(0xEEEEEE, 1);
    [v addSubview:line];
    
    UIView *lineLeft = [[UIView alloc] init];
    lineLeft.backgroundColor = UIColorFromRGB(0x000000, 1);
    [v addSubview:lineLeft];
    
    [lineLeft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(0);
        make.centerY.equalTo(v);
        make.size.mas_equalTo(CGSizeMake(4, 21));
    }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(10);
        make.trailing.mas_equalTo(-10);
        make.bottom.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];
    
    return v;
}

- (UILabel *)creatSectionHeadTitleLabel
{
    UILabel *l = [[UILabel alloc] init];
    l.font = [UIFont systemFontOfSize:15];
    l.textColor = UIColorFromRGB(0x333333, 1);
    l.textAlignment = NSTextAlignmentNatural;
    
    return l;
}

- (UILabel *)creatReviewsCountLabel
{
    UILabel *l = [[UILabel alloc] init];
    l.backgroundColor = UIColorFromRGB(0xececec, 1);
    l.textColor = UIColorFromRGB(0x333333, 1);
    l.font = [UIFont systemFontOfSize:12];
    l.textAlignment = NSTextAlignmentCenter;
    l.layer.cornerRadius = 8;
    l.layer.masksToBounds = YES;
    
    return l;
}

- (CGFloat)getReviewsTextWidth:(NSString *)text
{
    CGSize s = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, 16) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} context:nil].size;
    
    return s.width;
}

- (UIView *)creatSectionFootView
{
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 10)];
    v.backgroundColor = UIColorFromRGB(0xf0f0f0, 1);
    
    return v;
    
}

- (UIView *)creatMoreReviewsFootView
{
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 51)];
    v.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:LZLocalizedString(@"more_reviews", nil) forState:UIControlStateNormal];
    [button setTitleColor:UIColorFromRGB(0xff7a21, 1) forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button addTarget:self action:@selector(showMoreReviewsAction) forControlEvents:UIControlEventTouchUpInside];
    button.layer.borderColor = UIColorFromRGB(0xff7a21, 1).CGColor;
    button.layer.borderWidth = 0.5;
    button.layer.cornerRadius = 31/2.0;
    button.layer.masksToBounds = YES;
    [v addSubview:button];
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.centerX.equalTo(0);
        make.height.equalTo(31);
        make.width.equalTo(button.titleLabel.intrinsicContentSize.width+26);
    }];
    
    return v;
}

#pragma mark - Share

- (void)shareAction:(NSInteger)type videoModel:(LZVideoDetialModel *)vModel totleCount:(void(^)(NSInteger totleCount))totleCountBlock
{
    /* 分享视频 */
    SSDKPlatformType sharePlatformType = SSDKPlatformTypeUnknown;
    
    switch (type) {
        case 0:
            sharePlatformType = SSDKPlatformTypeSMS;
            break;
        case 1:
            sharePlatformType = SSDKPlatformTypeMail;
            break;
        case 2:
            sharePlatformType = SSDKPlatformTypeFacebook;
            break;
        case 3:
            sharePlatformType = SSDKPlatformTypeTwitter;
            break;
    }
    
    WS(wSelf);
    
    [TShareEventHandler shareWithShareURL:nil
                            shareImageUrl:@[[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,self.detailModel.videoPhoto]]
                               shareTitle:[NSString stringWithFormat:LZLocalizedString(@"share_video_title", nil),self.detailModel.promotionTitle]
                                shareText:[NSString stringWithFormat:LZLocalizedString(@"share_video_content", nil),self.detailModel.promotionTitle]
                                shareType:sharePlatformType
                                  topView:nil
                               stateBlock:^(SSDKResponseState state) {
                                   if (state == SSDKResponseStateSuccess) {
                                       // 分享成功
                                       [LZVideoPresenter saveShareCountWithVideoID:vModel.videoId ResultSuccess:^(NSInteger totleCount){
                                           wSelf.detailModel.shareCount = totleCount;
                                           [wSelf.tableView reloadData];
                                           if (totleCountBlock) {
                                               totleCountBlock(totleCount);
                                           }
                                       } ResultFailed:^(NSString *remind) {
                                           
                                       }];
                                   }
                               }];
    
    [self.shareView shareViewClose];
}

- (TShareView *)shareView {
    
    if (_shareView == nil) {
        _shareView = [[TShareView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    
    return _shareView;
}

#pragma mark - sheetView的GET方法
- (LZActionSheet*)sheetView {
    if (_sheetView) {
        return _sheetView;
    }
    
    LZActionSheet *sheet = [[LZActionSheet alloc] initWithFrame:self.navigationController.view.bounds];
    _sheetView = sheet;
    [self.navigationController.view addSubview:_sheetView];
    
    WS(weakSelf)
    _sheetView.ClickSheetBlock = ^(NSIndexPath *indexPath, id obj) {
        if (indexPath.section == 0) {
            [weakSelf callPhone:obj];
        }
    };
    
    return _sheetView;
}

- (void)showSheetView:(NSString*)phoneNumber {
    
    [self.sheetView ReloadTableViewArrayTitle:@[@[phoneNumber],@[LZLocalizedString(@"cancel", nil)]]];
    [self.sheetView ShowView];
}

@end
